package com.ilink.teacherservice.controller.bailian;


import com.ilink.ilinkcommon.domain.R;
import com.ilink.ilinkcommon.log.method.MethodLog;
import com.ilink.teacherservice.service.bailian.FileService;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/teacher/bailian")
public class FileController {

    @Autowired
    FileService fileService;

    @MethodLog
    @PostMapping("/upload/files")
    public R upload(@RequestParam("files") List<MultipartFile> files, String path) {
        try {
            return fileService.uploadFiles(files, path);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("上传失败");
        }
    }

    @MethodLog
    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file, String path,
                    @RequestParam(required = false, defaultValue = "") String newFilename) {
        try {
            return fileService.uploadFile(file, path, newFilename);
        } catch (Exception e) {
            return R.error("上传失败");
        }
    }

    @MethodLog
    @PostMapping("/create/category")
    public R createCategory(@RequestBody String jsonString) {
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            String path = jsonObject.getString("path");
            String directory = jsonObject.getString("directory");
            return fileService.createCategory(path, directory);
        } catch (Exception e) {
            return R.error("创建失败");
        }
    }

    @MethodLog
    @PostMapping("/delete/file")
    public R deleteFile(String path, String fileName) {
        // NOTE: 这里的fileName也要加后缀    
        try {
            return fileService.deleteFile(path, fileName);
        } catch (Exception e) {
            return R.error("删除失败");
        }
    }

    // TODO: 如果一个类目下面还有一个类目那么直接使用API的删除类目是失败的，因此采用递归删除，但是这样可能会出现单位时间访问API次数过多，请求失败的问题。具有流控机制
    @MethodLog
    @PostMapping("/delete/category")
    public R deleteCategory(String path) {
        try {
            return fileService.deleteCategory(path);
        } catch (Exception e) {
            return R.error("删除失败");
        }
    }
}
